<template>
  <el-dialog title="指定设备升级" v-model="openUpgrade" width="1200px" append-to-body :close-on-click-modal="false"
    @close="cancel">
    <el-form ref="formUpgradeRef" :model="formUpgrade" :rules="rulesUpgrade" label-width="80px">
      <el-form-item label="升级文件">
        <el-select v-model="formUpgrade.fileId" placeholder="请选择升级文件">
          <el-option v-for="item in ugradeOptions" :key="item.fileId" :label="item.fileName"
            :value="item.fileId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择设备">
        <span v-if="formUpgrade.sn.length > 0">
          <span v-for="(item, index) in formUpgrade.sn" :key="index">
            <span>{{ item }}</span>
            <span v-if="index != formUpgrade.sn.length - 1">，</span>
          </span>
        </span>
        <span v-else>未选择</span>
      </el-form-item>
      <el-table v-loading="loading" :data="infoList" v-show="is_choose" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="设备名称" align="center" prop="devName" />
        <el-table-column label="设备号" align="center" prop="sn" />
        <el-table-column label="信号值" align="center" prop="signalVal" />
        <el-table-column label="进度" align="center">
          <template #default="scope">
            <el-progress :text-inside="true" :stroke-width="24" :percentage="scope.row.percentage" striped striped-flow
              :color="colors" />
          </template>
        </el-table-column>
        <el-table-column label="实时速率" align="center">
          <template #default="scope">
            <span>{{ scope.row.speed }}B/s</span>
          </template>
        </el-table-column>
        <el-table-column label="预计升级时长" align="center">
          <template #default="scope">
            <span v-if="scope.row.percentage != 100">{{ scope.row.speedExtra }}</span>
            <span v-else>已完成</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="warning" @click="handleRoadRestart(scope.row.sn)" v-hasPermi="['operation:restart']">
              <span>重启设备</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryDev.pageNum" v-model:limit="queryDev.pageSize"
        @pagination="getDevList" />
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定升级</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { listDev } from "@/api/equipment/dev";
import { listUpgrade } from "@/api/upgrade/list";
import { restart } from "@/api/equipment/control";
import { getToken } from '@/utils/auth'
import { ElLoading } from 'element-plus'

const { proxy } = getCurrentInstance();

const { dev_status, dev_version } = proxy.useDict("dev_status", "dev_version");

const loading = ref(false)
const openUpgrade = ref(false)
const infoList = ref([])
const ugradeOptions = ref([])
const total = ref(0)
const ws_connect = ref(false)
const ws = ref(null)
const is_push = ref(false)
const uploadList = ref([])
const uploadData = ref([])
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const prod_uri = ref("wss://opr.gtcharger.com/prod-api/open/equipment/upgrade")
const dev_uri = ref("ws://192.168.113:8088/dev-api/open/equipment/upgrade")
const queryDev = ref({
  pageNum: 1,
  pageSize: 10,
  devStatus: "ON"
})
const colors = ref([
  { color: "grey", percentage: 0 },
  { color: "red", percentage: 10 },
  { color: "orangered", percentage: 20 },
  { color: "orange", percentage: 30 },
  { color: "yellow", percentage: 40 },
  { color: "darkorange", percentage: 50 },
  { color: "gold", percentage: 60 },
  { color: "cyan", percentage: 70 },
  { color: "blue", percentage: 80 },
  { color: "dodgerblue", percentage: 90 },
  { color: "yellowgreen", percentage: 100 },
])
const queryParams = ref({})
const formUpgrade = ref({
  sn: [],
  fileId: null,
})
const rulesUpgrade = ref({})
const is_choose = ref(true)

// 打开弹窗
function open(sn) {
  openUpgrade.value = true;
  if (sn == undefined) {
    is_choose.value = true;
    getDevList();
  } else {
    is_choose.value = false;
    formUpgrade.value.sn.push(sn);
  }
  getListUpgrade();
  wsInit();
}

// 暴露出去
defineExpose({
  open,
})

function getDevList() {
  loading.value = true;
  listDev(queryDev.value).then((response) => {
    infoList.value = response.rows;
    total.value = response.total;
    if (infoList.value.length > 0) {
      for (let i = 0; i < infoList.value.length; i++) {
        infoList.value[i].checked = false;
        infoList.value[i].offset = 0
        infoList.value[i].totalSize = 0
        infoList.value[i].lastOffset = 0
        infoList.value[i].speed = 0
        infoList.value[i].speedExtra = "-"
        infoList.value[i].percentage = 0
        for (let j = 0; j < infoList.value.length; j++) {
          if (formUpgrade.value.sn[j] == infoList.value[i].sn) {
            infoList.value[i].checked = true;
          }
        }
      }
    }
    loading.value = false;
  });
}

function getListUpgrade() {
  listUpgrade(queryParams.value).then((response) => {
    ugradeOptions.value = response.rows;
  });
}

function handleSelectionChange(selection) {
  formUpgrade.value.sn = selection.map((item) => item.sn);
}

function cancel() {
  openUpgrade.value = false;
  uploadData.value = []
  reset();
  if (ws.value) {
    wsClose();
  }
}

// 表单重置
function reset() {
  formUpgrade.value = {
    sn: [],
    fileId: null,
  };
  proxy.resetForm("formUpgradeRef");
}

function wsClose() {
  is_push.value = false
  ws.value.close();
  ws.value = null;
  ws_connect.value = false;
  console.log("关闭连接");
}

function wsInit() {
  is_push.value = true
  if (typeof WebSocket === "undefined") {
    console.log("您的浏览器不支持WebSocket");
    return;
  } else {
    let ws_uri = "";
    if (baseUrl == "/prod-api") {
      ws_uri = prod_uri.value;
      ws_uri = prod_uri.value + "?token=" + getToken();
      console.log("prod_uri", ws_uri);
    } else {
      ws_uri = dev_uri.value;
      ws_uri = dev_uri.value + "?token=" + getToken();
      console.log("dev_uri", ws_uri);
    }
    try {
      if (ws.value) ws.value = null;
    } catch (err) { }
    // 打开一个websocket
    var opts = { reconnection: false, transports: ['websocket'], extraHeaders: { 'Authorization': 'Bearer ' + getToken() } }
    ws.value = new WebSocket(ws_uri, [], opts);
    // ws.value = new WebSocket(ws_uri);
    // console.log(ws.value);
    ws.value.onopen = function (res) {
      console.log("websocket连接已链接", res);
      ws_connect.value = true;
    };
    ws.value.onmessage = function (res) {
      console.log("websocket数据", res);
      uploadList.value = JSON.parse(res.data)
      let data_list = []
      if (uploadData.value.length == 0) {
        for (let i = 0; i < uploadList.value.length; i++) {
          let data_str = {
            sn: uploadList.value[i].sn,
            offset: [],
          }
          data_str.offset.push(uploadList.value[i].offset)
          data_list.push(data_str)
          uploadList.value[i].lastOffset = uploadList.value[i].offset
          uploadList.value[i].speedExtra = uploadList.value[i].offset ? (Math.round((uploadList.value[i].totalSize - uploadList.value[i].offset) / uploadList.value[i].offset) + "s") : "-"
        }
        uploadData.value = data_list
      } else {
        for (let i = 0; i < uploadData.value.length; i++) {
          uploadData.value[i].offset.push(uploadList.value[i].offset)
          uploadList.value[i].lastOffset = uploadData.value[i].offset[uploadData.value[i].offset.length - 2]
          if (uploadList.value[i].offset > uploadList.value[i].lastOffset) {
            uploadList.value[i].speedExtra = uploadList.value[i].offset ? (Math.round((uploadList.value[i].totalSize - uploadList.value[i].offset) / (uploadList.value[i].offset - uploadList.value[i].lastOffset)) + "s") : "-"
          } else {
            uploadList.value[i].speedExtra = "-"
          }
        }
      }
      for (let i = 0; i < infoList.value.length; i++) {
        infoList.value[i].offset = 0
        infoList.value[i].totalSize = 0
        infoList.value[i].lastOffset = 0
        infoList.value[i].speed = 0
        infoList.value[i].speedExtra = "-"
        infoList.value[i].percentage = 0
        for (let j = 0; j < uploadList.value.length; j++) {
          if (infoList.value[i].sn == uploadList.value[j].sn) {
            infoList.value[i].offset = uploadList.value[j].offset
            infoList.value[i].totalSize = uploadList.value[j].totalSize
            infoList.value[i].lastOffset = uploadList.value[j].lastOffset
            infoList.value[i].speed = infoList.value[i].offset && infoList.value[i].lastOffset ? infoList.value[i].offset - infoList.value[i].lastOffset : 0
            infoList.value[i].speedExtra = uploadList.value[j].speedExtra
            infoList.value[i].percentage = uploadList.value[j].offset > uploadList.value[j].totalSize ? 100 : parseInt((uploadList.value[j].offset / uploadList.value[j].totalSize) * 100)
          }
        }
      }
      // console.log("websocket数据", uploadList.value);
      // console.log("采集数据", uploadData.value);
    }
    ws.value.onclose = function (res) {
      console.log("websocket连接已关闭", res);
      if (res.reason == "The web application is stopping") {
        Dialog.alert({
          title: "系统更新",
          message: "系统正在更新，即将退出系统",
          theme: "round-button",
        }).then(() => {
          // on close
          location.href = "/index";
        });
      }
    }
  }
}


// 设备指令--重启设备
function handleRoadRestart(sn) {
  let loadingInstance = ElLoading.service({
    lock: true,
    body: true,
    text: "正在重启",
    background: "rgba(0, 0, 0, 0.7)",
  });
  restart({ sn: sn })
    .then((response) => {
      loadingInstance.close();
      if (response.code == 0) {
        proxy.$modal.msgSuccess("重启成功");
      }
    })
    .catch((error) => {
      loadingInstance.close();
    });
}

function submitForm() {
  proxy.$refs["formUpgradeRef"].validate((valid) => {
    if (valid) {
      if (ws.value) {
        // if (uploadList.value.length == 0) {
        const data = []
        if (formUpgrade.value.sn.length > 0) {
          for (let i = 0; i < formUpgrade.value.sn.length; i++) {
            let data_str = {
              sn: formUpgrade.value.sn[i],
              fileId: formUpgrade.value.fileId
            }
            data.push(data_str)
          }
          const jsonString = JSON.stringify(data)
          ws.value.send(jsonString)
        } else {
          proxy.$modal.msgWarning("请选择升级的设备以及升级包");
        }
        // }
      }
    }
  });
}
</script>

<style scoped>
.pt20 {
  padding-top: 20px;
}
</style>
